<style>
    .layui-form-label {
        width: 100px;
    }

    .layui-input-block {
        margin-left: 130px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">分类名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text"
                                               placeholder="请输入分类名称"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog"
                                            lay-submit>查询
                                    </button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置
                                    </button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="customerTypeBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                        </div>
                        <div class="lay-btn-rt">

                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="customerTypeTable" lay-filter="customerTypeTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="customerTypeTableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
    {{# if(!d.isFinal){  }}
    <a class="layui-btn layui-btn-xs" lay-event="addSub">添加子分类</a>
    {{# } }}
    {{# if(!d.hasChild){ }}
    {{# } }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="customerTypeForm">
    <form lay-filter="customerTypeForm" class="layui-form model-form">
        <input name="id" type="hidden"/>

        <div class="layui-form-item" id="PID">
            <label class="layui-form-label">所属分类</label>
            <input name="parentId" type="hidden"/>
            <div class="layui-input-block" id="selectCategory">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">分类名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入分类名称" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block">
                <textarea id="remark" name="remark" placeholder="请输入描述" class="layui-textarea"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否终极分类</label>
            <div class="layui-input-block">
                <input name="isFinal" type="checkbox" lay-skin="switch" value="1" lay-text="是|否"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false"
                       lay-text="启用|停用"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="customerTypeFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>


<script type="text/html" id="childForm">
    <form lay-filter="customerTypeForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <input name="parentId" type="hidden"/>

        <div class="layui-form-item">
            <label class="layui-form-label">分类名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入分类名称" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入描述" class="layui-textarea"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否终极分类</label>
            <div class="layui-input-block">
                <input name="isFinal" type="checkbox" lay-skin="switch" value="1" lay-text="是|否"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false"
                       lay-text="启用|停用"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="childFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>


<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'tableTreeDj', 'config'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var tableTree = layui.tableTreeDj;

        // 渲染表格
        var insTb = tableTree.render({
            id: '#customerTypeTable',
            elem: '#customerTypeTable',
            url: config.base + 'enterprise/sell/admin/customerCategory/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: false,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers'}
                , {field: 'name', align: 'left', title: '客户分类名称'}
                , {field: 'remark', align: 'center', title: '描述'}
                , {
                    field: 'isFinal', align: 'center', title: '是否终极分类', templet: function (d) {
                        if (d.isFinal) {
                            return '是'
                        } else {
                            return '否'
                        }
                    }
                }
                , {
                    field: 'isDeleted', align: 'center', title: '状态', templet: function (d) {
                        if (d.isDeleted) {
                            return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" checked="' + d.isDeleted + '" lay-filter="isDeleted"  lay-text="启用|停用"/>';
                        } else {
                            return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" lay-filter="isDeleted"   lay-text="启用|停用"/>';
                        }
                    }
                }
                , {field: 'creatorName', align: 'center', title: '创建人'}
                , {field: 'createTime', align: 'center', title: '创建时间'}
                , {align: 'center', toolbar: '#customerTypeTableBar', title: '操作', width: 220}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                // var menuButton = config.getMenuButton(location.hash);
                // if(menuButton.indexOf("搜索") == -1){
                //     $('.layui-form.toolbar').remove();
                // }
                // if(menuButton.indexOf("修改") == -1){
                //     $("[lay-event='edit']").remove();
                // }
                // if(menuButton.indexOf("删除") == -1){
                //     $("[lay-event='del']").remove();
                // }
            }
        }, {keyPid: "parentId", title: "name"});

        // 工具条点击事件
        table.on('tool(customerTypeTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                data.eventType = 'edit';
                showEditModel(data, 'customerTypeForm', 'customerTypeFormSubmit');
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            } else if (obj.event === 'addSub') {
                //添加子级分类
                data.eventType = 'addSub';
                showEditModel(data, 'childForm', 'childFormSubmit', data.id);
            }
        });

        //监听排序
        table.on('sort(customerTypeTable)', function (obj) {
            table.reload('customerTypeTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: false}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', data => {
            insTb.reload({where: admin.resetSearch(data.field), page: {curr: 1}}, 'data');
        });

        form.on('switch(isDeleted)', function (obj) {
            if (obj.elem.checked) {
                enable(obj.value)
            } else {
                disable(obj.value)
            }
        })

        function enable(id) {
            admin.req('enterprise/sell/admin/customerCategory/enable', {id: id}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    insTb.reload('customerTypeTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'POST');
        }

        function disable(id) {
            admin.req('enterprise/sell/admin/customerCategory/disable', {id: id}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    insTb.reload('customerTypeTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'POST');
        }

        // 添加按钮点击事件
        $('#customerTypeBtnAdd').click(function () {
            showEditModel(undefined, 'customerTypeForm', 'customerTypeFormSubmit');
        });

        // 显示编辑弹窗
        function showEditModel(data, formId, submitButton, parentIdVal) {
            let finalCategoryIds = [];
            //加载终极分类
            admin.req('enterprise/sell/admin/customerCategory/list', {limit: 9999}, function (res) {
                if (res.code == 200) {
                    if (res.data != null) {
                        for (let i = 0; i < res.data.length; i++) {
                            if (res.data[i].isFinal == 'yes') {
                                finalCategoryIds.push(res.data[i].id)
                            }
                        }
                    }
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'get', false);

            admin.open({
                type: 1,
                area: '660px',
                offset: '65px',
                title: parentIdVal ? '添加子分类' : (data ? '编辑客户分类' : '添加客户分类'),
                content: $('#' + formId).html(),
                success: function () {
                    var eventType = data ? data.eventType : '';

                    function treeEach(treeData, ids) {
                        $.each(treeData, function (i, val) {
                            if (customContains(ids, val.value)) {
                                val.disabled = true;
                            }
                            if (val.children && val.children.length > 0) {
                                treeEach(val.children, ids);
                            }
                        });
                    }

                    let customContains = function (box, val) {
                        for (let i = 0; i < box.length; i++) {
                            if (box[i] == val) {
                                return true;
                            }
                        }
                        return false;
                    };


                    if (formId != 'childForm') {
                        xmSelect.render({
                            el: '#selectCategory',
                            model: {label: {type: 'text'}},
                            radio: true,
                            clickClose: true,
                            filterable: true,
                            tree: {
                                show: true,
                                strict: false,
                                expandedKeys: [-1],
                            },
                            tips: '顶级分类',
                            height: 'auto',
                            data() {
                                if (parentIdVal != undefined) {
                                    $("input[name='parentId']").val(parentIdVal);
                                }

                                let treeData = tableTree.getTree(data && parentIdVal == undefined ? data.parentId : parentIdVal, data ? data.id : null);
                                if (finalCategoryIds != null && finalCategoryIds.length > 0) {
                                    treeEach(treeData, finalCategoryIds);
                                }
                                return treeData;
                            },
                            on: function (data) {
                                //被选中的select的id,如果没有 -1
                                let parentId = data.arr.length > 0 ? data.change[0].value : -1;
                                $("input[name='parentId']").val(parentId);
                            },
                        });
                    }
                    //data 非空取值names
                    if (!config.isEmptyObject(data)) {
                        data.name = data.name.indexOf("</span>") > 0 ? data.name.split("</span>")[1] : data.name;
                        data.name = data.name.indexOf("&nbsp; &nbsp;") > 0 ? data.name.split(" &nbsp; &nbsp;").length > 2 ? data.name.split(" &nbsp; &nbsp;")[2] : data.name.split(" &nbsp; &nbsp;")[1] : data.name;
                    }
                    //添加子级渲染所属分类
                    if (formId == 'childForm') {
                        data.code = '';
                        data.name = '';
                        data.description = '';
                        data.status = '';
                        form.val(formId, data);
                        $("form input[name='parentId']").val(data.id);
                        data = undefined;
                    }

                    if (data) {
                        var option = $("form select[name='isFinal']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.isFinal == item.text) {
                                data.isFinal = item.value;
                            }
                        });
                    }
                    form.val('customerTypeForm', data);
                    // 表单提交事件
                    form.on('submit(' + submitButton + ')', function (d) {
                        layer.load(2);
                        if (d.field.parentId == null || d.field.parentId == '') {
                            d.field.parentId = -1
                        }
                        var isDeleted = $("form input[name='isDeleted']").prop("checked");
                        if (!isDeleted) {
                            d.field.isDeleted = false;
                        } else {
                            d.field.isDeleted = true;
                        }
                        var isFinal = $("form input[name='isFinal']").prop("checked");
                        if (!isFinal) {
                            d.field.isFinal = false;
                        } else {
                            d.field.isFinal = true;
                        }
                        if (eventType == 'addSub') {
                            d.field.id = undefined;
                        }
                        admin.req(data ? 'enterprise/sell/admin/customerCategory/update' : 'enterprise/sell/admin/customerCategory/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                insTb.reload('customerTypeTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/sell/admin/customerCategory/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }


    });
</script>